package com.kkwrite.regimen.consumer.controller.item;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.kkwrite.regimen.common.entity.dto.OutDTO;
import com.kkwrite.regimen.consumer.controller.constant.Constant;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/** 
 * 项目模块 
 *
 * @author Soosky Wang
 * @date 2018年7月20日 下午10:46:05 
 * @version 1.0.0
 */
@RestController
@RequestMapping("/item")
@Api(value = "项目模块")
public class ItemController {
	
	private static final Logger logger = LoggerFactory.getLogger(ItemController.class);

	private static final List<Integer> INDEX_SORT_PARAM_ALLOWABLE_LIST = Arrays.asList(1, 2, 3);
	private static final List<Integer> INDEX_SORT_TYPE_ALLOWABLE_LIST = Arrays.asList(1, 2);
	
	@Resource(name = "restTemplate")
	private RestTemplate restTemplate;

	@ApiOperation(value = "根据项目 id 查询项目详情")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "city", value = "所在城市", required = true, dataType = "String", paramType = "path")
	})
	@SuppressWarnings("rawtypes")
	@GetMapping("/getitemdetail/{itemId}")
	public OutDTO getItemDetail(@PathVariable Long itemId,@RequestParam String city) {
		if (logger.isDebugEnabled()) {
			logger.debug("ItemController.getItemDetail(), itemId = {}", itemId);
		}
		
		OutDTO outDTO;
		try {
			// 查询项目详情
			String url = Constant.SERVICE_PREFIX + "/item/getitemdetail/" + itemId+"?city="+city;
			outDTO = restTemplate.getForObject(url, OutDTO.class);
	/*		if ("true".equalsIgnoreCase(outDTO.getSuccess())) {
				// 根据项目 id 查询项目店铺
				String shopNumUrl = Constant.SERVICE_PREFIX + "/item/countshopnumbyitemid/" + itemId;
				OutDTO shopNumOutDTO = restTemplate.getForObject(shopNumUrl, OutDTO.class);
				Map shopNumMap = (LinkedHashMap) shopNumOutDTO.getData();
				Integer shopNum = (Integer) shopNumMap.get("shopNum");
				
				Map shopMap = (LinkedHashMap) outDTO.getData();
				shopMap.put("shopNum", shopNum);
			}*/
			return outDTO;
		} catch (RestClientException e) {
			logger.error("查询项目信息出错，itemId = " + itemId + "_" + e.getMessage());
			e.printStackTrace();
			return new OutDTO("failed", e.getMessage());
		}
	}

	@GetMapping(value = "/review/{itemId}")
	@HystrixCommand(fallbackMethod = "getItemReviewError")
	@ApiOperation(value = "查询项目评价接口")
	@ApiImplicitParam(name = "itemId", value = "项目ID", required = true, dataType = "int", paramType = "path", allowableValues = "range(0, infinity)")
	public OutDTO getItemReview(@PathVariable Integer itemId) {
		if (itemId == null || itemId <= 0) {
			return new OutDTO("false", "入参不合法");
		}
		return restTemplate.getForObject(Constant.SERVICE_PREFIX + "/item/review/" + itemId, OutDTO.class);
	}

	public OutDTO getItemReviewError(Integer itemId) {
		return new OutDTO("false", "服务异常！");
	}

	@GetMapping(value = "/indexpageable/{city}")
	@HystrixCommand(fallbackMethod = "getIndexItemPageableError")
	@ApiOperation(value = "分页查询首页项目数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "city", value = "所在城市", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "itemType", value = "项目类型(1-养生  2-美容)", required = true, dataType = "int", paramType = "query"),
			@ApiImplicitParam(name = "sort", value = "排序字段（1价格2人气3评价）", dataType = "int", paramType = "query",
					allowableValues = "{1,2,3}", defaultValue = "1"),
			@ApiImplicitParam(name = "sortType", value = "排序方式（1正序2逆序）", dataType = "int", paramType = "query",
					allowableValues = "{1,2}", defaultValue = "1"),
			@ApiImplicitParam(name = "page", value = "页码", dataType = "int", paramType = "query",
					allowableValues = "range[0, infinity)", defaultValue = "0"),
			@ApiImplicitParam(name = "pageSize", value = "每页数量", dataType = "int", paramType = "query",
					allowableValues = "range[1, infinity)", defaultValue = "5"),
	})
	public OutDTO getIndexItemPageable(@PathVariable String city,Integer itemType, Integer sort, Integer sortType, Integer page, Integer pageSize) {
		if (StringUtils.isBlank(city)) {
			return new OutDTO("false", "入参不合法");
		}
		if (sort != null && !INDEX_SORT_PARAM_ALLOWABLE_LIST.contains(sort)) {
			return new OutDTO("false", "入参不合法");
		}
		if (sortType != null && !INDEX_SORT_TYPE_ALLOWABLE_LIST.contains(sortType)) {
			return new OutDTO("false", "入参不合法");
		}
		if (itemType != null && (itemType!=1&&itemType!=2)) {
			return new OutDTO("false", "入参不合法");
		}
		if (page != null && page < 0) {
			return new OutDTO("false", "入参不合法");
		}
		if (pageSize != null && pageSize < 1) {
			return new OutDTO("false", "入参不合法");
		}
		if (sort == null) {
			sort = 1;
		}
		if (sortType == null) {
			sortType = 1;
		}
		if (page == null) {
			page = 0;
		}
		if (pageSize == null) {
			pageSize = 5;
		}
		if(itemType==null){
			itemType=3;
		}
		return restTemplate.getForObject(Constant.SERVICE_PREFIX + "/item/indexPageable/"
				+ city
				+"?itemType="+itemType
				+ "&sort=" + sort
				+ "&sortType=" + sortType
				+ "&page=" + page
				+ "&pageSize=" + pageSize, OutDTO.class);
	}

	public OutDTO getIndexItemPageableError(String city,Integer itemType, Integer sort, Integer sortType, Integer page, Integer pageSize) {
		return new OutDTO("false", "服务异常！");
	}

	@GetMapping(value = "/querySysItems")
	@ApiOperation(value = "分页查系统项目列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "page", value = "获取第page页数据", required = true, allowableValues = "[0, infinity]", paramType = "query", dataType = "int"),
		@ApiImplicitParam(name = "size", value = "每页size条记录", required = true, allowableValues = "[1, infinity]", paramType = "query", dataType = "int"),
		@ApiImplicitParam(name = "sortType", value = "按时间排序的排序类型", defaultValue = "2", allowableValues = "{1, 2}", paramType = "query", dataType = "int") 
	})
	public OutDTO querySysItems(
			@RequestParam(required = false) Integer page,
			@RequestParam(required = false) Integer size,
			@RequestParam(required = false) Integer sortType,
			HttpServletRequest request) {
		if (sortType != null && !INDEX_SORT_TYPE_ALLOWABLE_LIST.contains(sortType)) {
			return new OutDTO("false", "入参不合法");
		}
		if (page != null && page < 0) {
			return new OutDTO("false", "入参不合法");
		}
		if (size != null && size < 1) {
			return new OutDTO("false", "入参不合法");
		}
		if (sortType == null) {
			sortType = 1;
		}
		if (page == null) {
			page = 0;
		}
		if (size == null) {
			size = 5;
		}
		return restTemplate.getForObject(Constant.SERVICE_PREFIX + "/item/querySysItems"
				+"?page="+page
				+ "&size=" + size
				+ "&sortType=" + sortType
				, OutDTO.class);
	}
}
